package com.sgcc.sx.pmos.common.utils;

import android.text.Editable;
import android.text.TextWatcher;
import android.widget.EditText;

import java.math.BigDecimal;

public class LengthTextWatcher implements TextWatcher {
    private EditText editText;

    public LengthTextWatcher(EditText editText) {
        this.editText = editText;
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

    }

    @Override
    public void afterTextChanged(Editable s) {
        editText.removeTextChangedListener(this);
        String str = s.toString();
        if (str.length() > 0) {
            if (str.contains(".")) {
                String before = str.substring(0, str.indexOf("."));
                String after = str.substring(str.indexOf("."), s.length());
                if (before.length() > 1) {
                    if (before.startsWith("0")) {
                        BigDecimal num = new BigDecimal(before);
                        String newstr = num.toPlainString() + after;
                        editText.setText(newstr);
                        editText.setSelection(newstr.length());
                    }
                }
            } else {
                if (str.startsWith("0")) {
                    BigDecimal num = new BigDecimal(str);
                    editText.setText(num.toPlainString());
                    editText.setSelection(num.toPlainString().length());
                }
            }
        }
        editText.addTextChangedListener(this);

    }
}
